const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const {CleanWebpackPlugin} = require('clean-webpack-plugin');
const env = require('./env');

const baseConfig = {
  entry: [path.resolve(__dirname, '../src/index.js'), path.resolve(__dirname, '../index.html')],
  output: {
    filename: 'js/built.js',
    path: path.resolve(__dirname, '../dist')
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        loader: 'babel-loader',
        options: {
          presets: [
            [
              '@babel/preset-env',
              {
                // 按需加载
                useBuiltIns: 'usage',
                //指定core-js 版本
                corejs: {
                  version: 3
                },
                // 指定兼容性做到哪个版本
                targets: {
                  chrome: '60',
                  firefox: '60',
                  ie: '9',
                  safari: '10',
                  edge: '17'
                }
              }
            ]
          ]
        }
      },
      {
        test: /\.(jpe?g|png|gif)$/,
        type: 'asset',
        //解析
        parser: {
          //转base64的条件
          dataUrlCondition: {
            maxSize: 8 * 1024, // 8kb
          }
        },
        generator: {
          //与output.assetModuleFilename是相同的,这个写法引入的时候也会添加好这个路径
          filename: 'img/[name].[hash:6][ext]',
          //打包后对资源的引入，文件命名已经有/img了
          publicPath: './'
        },
      },
      {
        test: /\.html$/,
        loader: 'html-loader'
      },
      {
        exclude: /\.(js|css|less|jpg|png|jpeg|gif|html)$/,
        type: 'asset',
        parser: {
          dataUrlCondition: {
            maxSize: 8 * 1024,
          }
        },
        generator: {
          filename: 'others/[name]_[hash:8].[ext]',
          publicPath: './'
        }
      } 
    ]
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: path.resolve(__dirname, '../index.html')
    }),
    new webpack.DefinePlugin({
      "process.env": env
    }),
    new CleanWebpackPlugin()
  ]
}

module.exports = baseConfig;
